import React, {useEffect, useRef, useState} from 'react';
import classes from './index.module.scss'
import {Avatar, Button, Card, Divider, Empty, Form, Input, message, Modal, Select, Skeleton, Space, Upload} from "antd";
import Meta from "antd/es/card/Meta";
import Article from "../../../component/frontDesk/Article";
import {useDispatch, useSelector} from "react-redux";
import axios from "axios";
import {LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import {reqUpdateUser} from "../../../api/backStage/backStageApi";
import {updateArticleList} from "../../../store/frontDesk/articleSlice";
import {reqArticleIntro, reqDeleteNote, reqGetNoteList} from "../../../api/frontDesk/frontDeskApi";
import moment from "moment";
import {useLocation} from "react-router-dom";

const tabList = [
    {
        key: 'article',
        tab: '我的文章',
    },
    {
        key: 'note',
        tab: '我的笔记',
    },
];


const style = {
    position: "relative",
    display: 'flex',
    justifyContent: "space-between",
    flexDirection: 'column',
    width: "100%",
    height: "100%",
    padding: "18px"
}

//添加用户表单的配置
const formItemLayout = {
    labelCol: {
        xs: {
            span: 16,
        },
        sm: {
            span: 8,
        },
    },
    wrapperCol: {
        xs: {
            span: 8,
        },
        sm: {
            span: 8,
        },
    },
};


//上传头像的方法
const getBase64 = (img, callback) => {
    const reader = new FileReader();
    console.log(reader)
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};
const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
};


const UserCenter = () => {
    const [activeTabKey1, setActiveTabKey1] = useState('article');
    const [loading, setLoading] = useState(true);
    const [noteList, setNoteList] = useState([]);
    const [noteOpen, setNoteOpen] = useState(false);
    const [noteContent, setNoteContent] = useState('');
    const [deleteNoteOpen, setDeleteNoteOpen] = useState(false);
    const [deleteNoteId, setDeleteNoteId] = useState('');

    const {homeArticleList} = useSelector(state => state.persistedReducer.article)
    const [editInfo, setEditInfo] = useState(false)
    const {userAllInfo} = useSelector(state => state.persistedReducer.user)

    const userFormRef = useRef()
    const [form] = Form.useForm();

    //用户表格数据
    //展开操作
    const {Option} = Select;
    const [imageUrl, setImageUrl] = useState([]);

    const {state} = useLocation()


    useEffect(() => {
        if (userAllInfo) {
            getNoteList()
            setTimeout(() => {
                setLoading(false)
            }, 300)
        }
    }, [state])

    useEffect(() => {
        setImageUrl([userAllInfo.user_avatar]);
    }, [userAllInfo]);

// 使用 useEffect 监听 imageUrl 的变化
    useEffect(() => {
        form.setFieldsValue({
            ...userAllInfo,
            user_avatar: imageUrl
        });
    }, [imageUrl, form]);

    const getNoteList = async () => {
        const result = await reqGetNoteList({user_id: userAllInfo.id})
        if (result.status === 0) {
            setNoteList(result.data)
        }
    }

    const edit = () => {
        setEditInfo(true)
    }


    const note = (item) => {
        return (
            <div key={item.id}
                 style={{width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                <div onClick={() => {
                    setNoteContent(item.content)
                    setNoteOpen(true)
                }} className={classes.Note}>
                    <div>
                        标题：{item.title}
                    </div>
                    <div>
                        编写时间：{moment(item.create_time).format('YYYY-MM-DD HH:mm:ss')}
                    </div>
                </div>
                <Button type="primary" onClick={() => {
                    setDeleteNoteId(item.id)
                    setDeleteNoteOpen(true)
                }}>删除</Button>
            </div>
        )
    }

    //删除文章
    const confirmDelete = async () => {
        console.log(1)
    }

    const contentList = {
        article: <div style={{height: 450, paddingBottom: 30, overflow: 'auto'}}>
            {
                homeArticleList.filter((item) => item.author_name === userAllInfo.nickname).length === 0 ?
                    <Empty description="暂未编写文章" /> : homeArticleList.filter((item) => item.author_name === userAllInfo.nickname)
                        .map((item) => (<Article onDelete={() => confirmDelete()} key={item.id} article={item}/>))
            }
        </div>,
        note: <div style={{height: 450, paddingBottom: 30, overflow: 'auto'}}>
            {
                noteList.length === 0 ? <Empty/> :
                    noteList.map((item) => (
                        note(item)))
            }
        </div>,
    };

    const onTab1Change = (key) => {
        setActiveTabKey1(key);
    };

    //删除草稿成功事件
    const deleteNoteOk = async () => {
        console.log(deleteNoteId)
        const result = await reqDeleteNote({note_id: deleteNoteId})
        if (result.status === 0) {
            setDeleteNoteOpen(false)
            message.success('删除笔记成功!')
            getNoteList()
        } else {
            message.error('删除笔记失败!')
        }
    }


    const updateUserOk = async () => {
        if (editInfo) {
            try {
                const fd = form.getFieldValue()
                const result = await reqUpdateUser({user_id: userAllInfo.id, fd})
                if (result.status === 0) {
                    setTimeout(async () => {
                        message.success('修改信息成功')
                        setEditInfo(false)
                    }, 1000);
                    console.log(result.data)
                } else {
                    message.error('修改信息失败')
                }
            } catch (err) {
                message.error(err)
            }
        }
    }


    //自定义上传
    const customRequest = async (options) => {
        // console.log(options)
        const {onSuccess, onError, file} = options;
        const fmData = new FormData()
        const config = {
            headers: {"content-type": "multipart/form-data"},
        };
        fmData.append("file", file);
        try {
            const res = await axios.post(
                `${process.env.REACT_APP_API_URL}/admin/user-table/uploads`,
                fmData,
                config
            );
            const {url} = res.data;
            const fileObj = {
                uid: res.data.id,
                name: file.name,
                status: "done",
                url,
            };
            onSuccess(fileObj);
            console.log("server res: ", res);
        } catch (err) {
            console.log("Error: ", err);
            onError(err);
        }
    }
    //上传组件选择图片的事件
    const handleChange = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            console.log(info)
            getBase64(info.file.originFileObj, (url) => {
                setLoading(false);
                setImageUrl([url]);
            });
        }
    };
    const normFile = (e) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList
    }
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined/> : <PlusOutlined/>}
            <div style={{marginTop: 8,}}></div>
        </div>
    )

//重置添加用户表单

    const reset = () => {
        setImageUrl(null)
        userFormRef.current.resetFields()
    }


    //密码校验
    const validatePassword = (_, value) => {
        if (!value) {
            return Promise.reject('请输入密码!');
        }
        if (value.length < 6) {
            return Promise.reject('密码长度至少是6位!');
        }
        return Promise.resolve();
    };

    //确认密码校验
    const validateConfirmPassword = (_, value) => {
        if (!value) {
            return Promise.reject('请确认密码!');
        }
        if (value !== form.getFieldValue('password')) {
            return Promise.reject('两次密码输入必须一致!');
        }
        return Promise.resolve();
    };


    return (
        <div className={classes.UserCenter}>
            {
                editInfo ?
                    <Card style={{width: 980}}>
                        <Form
                            {...formItemLayout}
                            ref={userFormRef}
                            form={form}
                            name="add"
                            onFinish={updateUserOk}
                            scrollToFirstError
                        >
                            <Form.Item
                                name="phone"
                                label="手机号"
                                rules={[
                                    {
                                        type: 'phone',
                                        message: '手机号不符合规范!',
                                    },
                                    {
                                        required: true,
                                        message: '请输入手机号!',
                                    },
                                ]}
                            >
                                <Input/>
                            </Form.Item>

                            <Form.Item
                                name="password"
                                label="密码"
                                rules={[{validator: validatePassword}]}
                                hasFeedback
                            >
                                <Input.Password/>
                            </Form.Item>

                            {
                                editInfo ?
                                    <Form.Item
                                        name="confirm"
                                        label="确认密码"
                                        dependencies={['password']}
                                        hasFeedback
                                        rules={[{validator: validateConfirmPassword}]}
                                    >
                                        <Input.Password/>
                                    </Form.Item> : null
                            }


                            <Form.Item
                                name="nickname"
                                label="昵称"
                                tooltip="你期望取一个什么昵称?"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入昵称!',
                                        whitespace: true,
                                    },
                                ]}
                            >
                                <Input/>
                            </Form.Item>

                            <Form.Item
                                name="user_email"
                                label="邮箱"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入邮箱!',
                                        whitespace: true,
                                    },
                                ]}
                            >
                                <Input/>
                            </Form.Item>

                            <Form.Item
                                name="gender"
                                label="性别"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择性别!',
                                    },
                                ]}
                            >
                                <Select placeholder="选择性别">
                                    <Option value="男">男</Option>
                                    <Option value="女">女</Option>
                                </Select>
                            </Form.Item>

                            <Form.Item
                                name="user_avatar"
                                label="更换头像"
                                rules={[
                                    {
                                        required: true,
                                        message: '请上传头像!',
                                    },
                                ]}
                                getValueFromEvent={normFile}
                                valuePropName="fileList">

                                <Upload
                                    listType="picture-card"
                                    showUploadList={false}
                                    beforeUpload={beforeUpload}
                                    onChange={handleChange}
                                    maxCount={1}
                                    customRequest={customRequest}
                                >
                                    {imageUrl ? (
                                        <img
                                            src={imageUrl}
                                            alt="avatar"
                                            style={{width: '100%'}}
                                        />
                                    ) : (uploadButton)}
                                </Upload>
                            </Form.Item>

                            <div className={classes.FooterBtn}>
                                <Space>
                                    <Form.Item>
                                        <Button onClick={reset} type="primary">
                                            重置表单
                                        </Button>
                                    </Form.Item>
                                    <div style={{display: 'flex'}}>
                                        <Space>
                                            <Form.Item>
                                                <Button onClick={() => {
                                                    setEditInfo(false)
                                                }}>
                                                    取消
                                                </Button>
                                            </Form.Item>
                                            <Form.Item>
                                                <Button type="primary" htmlType="submit">
                                                    {editInfo ? "确认修改" : ""}
                                                </Button>
                                            </Form.Item>
                                        </Space>
                                    </div>
                                </Space>
                            </div>
                        </Form>
                    </Card>
                    :
                    <>
                        <div style={{width: "75%"}}>
                            <Card bodyStyle={style} className={classes.UserInfo}>
                                <Skeleton loading={loading} avatar active>
                                    <Meta
                                        className={classes.UserMeta}
                                        avatar={<Avatar size={80} src={userAllInfo.user_avatar}/>}
                                        title={<span>{userAllInfo.nickname}</span>}
                                        description={
                                            <span>签名：{userAllInfo.user_signature ? userAllInfo.user_signature :
                                                <span>暂无签名</span>}
                                            </span>}
                                    />
                                    <Divider/>
                                    <Button onClick={() => edit()} type="link" style={{width: 10}}>修改个人信息</Button>
                                </Skeleton>
                            </Card>
                            <Card
                                style={{marginTop: 15}}
                                tabList={tabList}
                                activeTabKey={activeTabKey1}
                                onTabChange={(key) => {
                                    onTab1Change(key);
                                }}
                            >
                                {contentList[activeTabKey1]}
                            </Card>
                        </div>
                        <div className={classes.MyConcern}>
                            <div>我的会员等级</div>
                            <span style={{color: 'blue'}}>{userAllInfo.role ? userAllInfo.role : '暂未开通'}</span>
                        </div>
                    </>
            }
            <Modal
                onCancel={() => setNoteOpen(false)}
                onOk={() => setNoteOpen(false)}
                title={<h3>我的笔记</h3>}
                open={noteOpen}
                width={800}
                bodyStyle={{
                    height: "200px",
                    padding: "40px",
                }}
                okText="确认"
                cancelText="取消"
            >
                {noteOpen && <div dangerouslySetInnerHTML={{__html: noteContent}}></div>}
            </Modal>
            <Modal
                onCancel={() => setDeleteNoteOpen(false)}
                title={<h3>删除所选笔记</h3>}
                open={deleteNoteOpen}
                width={500}
                okText="确认"
                cancelText="取消"
                onOk={() => deleteNoteOk()}
            >
                <p> 确认要删除该笔记吗？</p>
            </Modal>
        </div>
    );
};

export default UserCenter;